#include <unistd.h>//Linux系统下网络通讯的头文件集合
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <malloc.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <stdarg.h>
#include <fcntl.h>
#include <fcntl.h>
#include <iostream>
#include <opencv2/opencv.hpp>  
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/videoio/videoio.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <math.h>
#include "../include/car_picture_upload.h"

using namespace cv;
using namespace std;

enum
{
	PORT = 0X5432
};


struct Pic
{
    char encodeImg[64535];
};

void picture_upload(cv::Mat image)
{
    //image.set(CV_CAP_PROP_FRAME_WIDTH,512);
    //image.set(CV_CAP_PROP_FRAME_HEIGHT,256);
	int m_sockClient;
	Pic pi;
	memset((void*)&pi, 0, sizeof(Pic));
	if ((m_sockClient = socket(AF_INET, SOCK_DGRAM, 0)) < 0)    //创建socket句柄，采用UDP协议
	{
		printf("create socket error: %s(errno: %d)\n", strerror(errno), errno);
		return ;
	}
	sockaddr_in m_servaddr;
	memset(&m_servaddr, 0, sizeof(m_servaddr));  //初始化结构体
	m_servaddr.sin_family = AF_INET;           //设置通信方式
	m_servaddr.sin_port = htons(PORT);         //设置端口号

	bind(m_sockClient, (sockaddr*)&m_servaddr, sizeof(m_servaddr));//绑定端口号
	//VideoCapture capture(1);
	//capture.set(CV_CAP_PROP_FRAME_WIDTH,1280);
    //capture.set(CV_CAP_PROP_FRAME_HEIGHT,480);
	//Mat image;
	if (image.empty())    //如果照片为空则退出
	{
	    printf("empty image\n\n");
	    return ;
	}
	std::vector<uchar> data_encode;
	std::vector<int> quality;

	quality.push_back(CV_IMWRITE_JPEG_QUALITY);
	quality.push_back(80);//进行80%的压缩
	imencode(".jpg", image, data_encode,quality);//将图像编码
	//char encodeImg[65535];
	int nSize = data_encode.size();
	for (int i = 0; i < nSize; i++)
	{
	    pi.encodeImg[i] = data_encode[i];
	}
	//pi.imu = 200;
	m_servaddr.sin_addr.s_addr = inet_addr("192.168.2.1");
	m_servaddr.sin_port = htons(0x2345);//设置需要发送的IP和端口号
	//cout << "1" << endl;
	//sendto(m_sockClient, encodeImg, nSize, 0, (const sockaddr*)& m_servaddr, sizeof(m_servaddr));
	int send = sendto(m_sockClient, (void*)&pi, sizeof(Pic), 0, (const sockaddr*)& m_servaddr, sizeof(m_servaddr));
	//int sent = send(m_sockClient, (void*)&pi, sizeof(Pic_imu), 0);
	cout << "Image send: "<<send << endl;
	//memset(&encodeImg, 0, sizeof(encodeImg));  //初始化结构体
}

